import { TUILogin } from '@tencentcloud/tui-core'
import TUIChatEngine, {
  TUIChatService,
  TUIStore,
  TUIGlobal,
  StoreName,
  TUIConversationService,
  TUIGroupService,
} from '@tencentcloud/chat-uikit-engine'
import { genTestUserSig } from '@/TUIKit'
import { sendGroupMessage, createSessionRecord } from '@/api/TIM'

/**
 * 登录 Chat SDK
 */
export const LoginTIM = async (userID: string) => {
  if (!userID) {
    console.info(`>>>>>>>>>>>>>>> userID为空，TIM 无法登录`, userID)
  }

  // 必填信息
  const config = {
    userID,
    SDKAppID: 1600041564,
    secretKey: '75fbae19cc09a2a5320c6d60686f19cf4151a0647fcfc0e8a73e99e9efc6b060',
  }

  // 获取 userSig
  const { userSig } = genTestUserSig(config)
  console.log('userSig', userSig)

  // 登录 Chat SDK
  await TUIChatEngine.login({
    SDKAppID: config.SDKAppID,
    userID,
    userSig,
    useUploadPlugin: true,
    useProfanityFilterPlugin: false,
  }).then(res => {
    console.warn(`>>>>>>>>>>>>>>> TIM 登录成功(${userID}) `, res)
  })

  /**
   * 设置 SDK 日志输出级别，详细分级
   * 0 普通级别，日志量较多，接入时建议使用
   * 1 release级别，SDK 输出关键信息，生产环境时建议使用
   * 2 告警级别，SDK 只输出告警和错误级别的日志
   * 3 错误级别，SDK 只输出错误级别的日志s
   * 4 无日志级别，SDK 将不打印任何日志
   */
  TUIChatEngine.setLogLevel(1)

  // UI 层监听当前会话消息列表更新通知
  // let onMessageListUpdated = function (messageList) {
  //   console.warn('-- messageList ---------->', messageList)
  // }
  // TUIStore.watch(StoreName.CHAT, {
  //   newMessageList: onMessageListUpdated,
  // })

  // UI 层监听会话列表更新通知
  // let onConversationListUpdated = function (conversationList) {
  //   console.warn('-- conversationList ---------->', conversationList)
  // }
  // TUIStore.watch(StoreName.CONV, {
  //   conversationList: onConversationListUpdated,
  // })
}

/**
 * 登出 Chat SDK
 */
export const LogoutTIM = async () => {
  if (TUIChatEngine.userID) {
    // 清空当前会话ID
    await TUIConversationService.switchConversation('')

    // 登出 Chat SDK
    await TUIChatEngine.logout()

    // 登录成功后进行相关业务逻辑处理
    console.log(`TIM 登出: `, TUIChatEngine)
  }
}

/**
 * 创建单聊会话
 */
export const CreateConversation = async userID => {
  // userID 强转 为字符串
  userID = String(userID)

  const founder = (await TUIChatEngine).userID
  console.log('DC: 创建会话', founder, founder)
  if (!founder) return

  // 创建会话
  const conversationID = `C2C${userID}`
  const conversationData = await TUIConversationService.getConversationProfile(conversationID)
  console.warn('DC: TIM 创建会话成功', conversationData.data.conversation)

  // 进入会话
  SwitchConversation(conversationID)

  // 发送欢迎语
  // SendMessage(userID, '**与**互相喜欢，开始互相聊天')

  return conversationData
}

/**
 * 切换会话
 */
export const SwitchConversation = conversationID => {
  TUIConversationService.switchConversation(conversationID).catch(error => {
    console.warn('switch conversation failed:', error)
  })

  TUIGlobal?.global?.navigateTo({
    url: '/TUIKit/components/TUIChat/index',
  })
  console.warn('DC: 切换会话成功', conversationID)
}

/**
 * 发送消息
 */
export const SendMessage = async (MSG_TYPE, to, conversationType, payload: {}, callback) => {
  // let currentConversation

  // await TUIStore.watch(StoreName.CONV, {
  //   currentConversation: conversation => {
  //     currentConversation = conversation
  //   },
  // })
  // console.log('---------->', currentConversation)

  const options = {
    to,
    conversationType,
    payload,
  }
  console.log('payload', payload)
  // 发送消息
  await TUIChatService[MSG_TYPE](options)

  // 回调
  callback()

  // DC：记录聊天信息
}

/**
 * 创建群组
 */
export const CreateGroup = async (
  memberList = [],
  groupType: string = '问诊',
  groupName: string = '群组'
) => {
  // 当前登录用户ID
  const { userID: founder } = await TUIChatEngine

  // 登录状态判断
  if (!founder) {
    console.log('DC: TIM 未登录')
    return
  } else {
    console.warn('DC: TIM 已登录成功', founder)
  }

  // 获取医生名称
  const { doctorName } = uni.getStorageSync('userInfo')
  const doctor = {
    userID: founder,
    userName: doctorName,
  }

  // 处理群成员列表
  let joinMemberList: object[] = []
  // 去除当前用户
  memberList = memberList
    .map(item => {
      if (item.userID !== String(founder)) {
        return item
      }
    })
    .filter(item => item)
  switch (groupType) {
    case '问诊':
      joinMemberList = [doctor, ...memberList]
      break
    case '会诊':
      joinMemberList = [doctor, ...memberList]
      break
    default:
      joinMemberList = [doctor]
      break
  }

  console.log('-- groupName ---------------------------------------', groupName)
  console.log('-- memberList ---------------------------------------', memberList)
  console.log('-- joinMemberList ---------------------------------------', joinMemberList)

  // 创建群组
  const NewGroup = await TUIGroupService.createGroup({
    type: TUIChatEngine.TYPES.GRP_PUBLIC,
    name: groupName,
    memberList: joinMemberList,
  }).catch(error => {
    console.log('-- createGroup ---------->', error)
  })

  if (NewGroup) {
    console.warn('DC: TIM 创建会话成功 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', NewGroup)
  } else {
    console.error('DC: TIM 创建会话失败 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
  }

  // 获取群组ID
  const { groupID } = NewGroup?.data?.group || ''

  // 邀请加入群组
  // if (groupType == '会诊') {
  //   console.log('>>>>>>>>>>>>>', groupType, memberList)

  //   const addMemberList = memberList.map(item => {
  //     return item?.userID
  //   })
  //   console.log('-- addMemberList ---------------------------------------', addMemberList)
  //   await AddGroupMember(groupID, addMemberList)
  // }

  try {
    // 获取群会话资料
    const getGroupMemberProfile = await TUIConversationService.getConversationProfile(
      `GROUP${groupID}`
    )

    console.log('会话资料', getGroupMemberProfile.data)

    // 创建会话记录
    createSessionRecord({
      groupId: groupID,
      conversationId: `GROUP${groupID}`,
      founder, // 创建人
      participants: memberList.map(item => item.userID).join(','), // 参与人
      conversation: JSON.stringify(getGroupMemberProfile.data.conversation),
    })
  } catch (error) {
    uni.showToast({
      title: error,
      duration: 2000,
      icon: 'none',
    })
  }

  // 设置成员名称
  joinMemberList.forEach(async item => {
    console.log('-- groupID ---------->', groupID)
    console.log('-- userID ---------->', item.userID)
    console.log('-- nameCard ---------->', item.userName)
    await TUIGroupService.setGroupMemberNameCard({
      groupID,
      userID: item.userID,
      nameCard: item.userName,
    }).catch(error => {
      console.log('-- setGroupMemberNameCard ---------->', error)
    })
  })

  // 更新群资料
  await TUIGroupService.updateGroupProfile({
    groupID,
    avatar: 'https://img0.baidu.com/it/u=2284996796,3838465017&fm=253&fmt=auto&app=138&f=JPEG',
    // muteAllMembers: true, // 全员禁言
    groupCustomField: [
      { key: 'diagnosis_type', value: groupType },
      { key: 'chat_status', value: '1' },
    ],
  })

  // 获取群成员资料
  // const getGroupMemberProfile = await TUIGroupService.getGroupMemberProfile({
  //   groupID,
  //   userIDList: ['4', '44'],
  // })

  // console.log('-- getGroupMemberProfile ---------->', getGroupMemberProfile)

  // 发送群系统消息
  // const message = {
  //   businessID: 'tip',
  //   type: 'highlight', // default | highlight | card | topbar |
  //   text: '医生已接诊，交流通道已开启，最长交流时长为48小时，请医患及时进行问诊',
  // }
  // SendGroupMessage(groupID, message)

  // 创建者发送欢迎语
  // const payload = {
  //   text: '您好，请问有什么可以帮助您的？',
  // }
  // await SendMessage('sendTextMessage', groupID, TUIChatEngine.TYPES.CONV_GROUP, payload, () => {
  //   // SwitchConversation(conversationID)
  // })

  // 进入会话
  const conversationID = `GROUP${groupID}`

  // 切换会话
  if (groupID) {
    setTimeout(() => {
      SwitchConversation(conversationID)
    }, 1000)
  }

  return NewGroup
}

/**
 * 获取群资料
 */
export const GetGroupProfile = async groupID => {
  const groupProfile = await TUIGroupService.getGroupProfile(groupID)
  console.warn('DC: TIM 获取群资料成功', groupProfile)

  return groupProfile
}

/**
 * 更新群资料
 */
export const UpdateGroupProfile = async (groupID: string, option: {}) => {
  console.log('=====================', groupID, option)

  return await TUIGroupService.updateGroupProfile({
    groupID,
    ...option,
  })
}

/**
 *  添加群成员
 */
export const AddGroupMember = async (groupID = '', userIDList: string[] = []) => {
  console.log('AddGroupMember >>>>>>>>>>>>', groupID, userIDList)

  return await TUIGroupService.addGroupMember({
    groupID,
    userIDList,
  })
}

/**
 * 切换群组
 */
export const SwitchGroup = (groupID: string) => {
  TUIGroupService.switchGroup(groupID).catch(error => {
    console.warn('switch conversation failed:', error)
  })

  TUIGlobal?.global?.navigateTo({
    url: '/TUIKit/components/TUIChat/index',
  })
  console.warn('DC: 切换会话成功', groupID)
}

/**
 * 发送群组普通消息
 */
interface MessageTpye {
  businessID: string
  text: string
  type?: string
  title?: string
  buttonText?: string
  buttonUrl?: string
}
export const SendGroupMessage = (groupID: string, message: MessageTpye) => {
  console.log('SendGroupMessage >>>>>>>>>>>>', groupID, message)

  if (!groupID || !message) return

  try {
    // 发送群消息
    sendGroupMessage(groupID, message).catch(error => {
      console.log('-- sendGroupMessage ---------->', error)
      uni.showToast({
        title: error,
        duration: 2000,
        icon: 'none',
      })
    })
  } catch (error) {
    uni.showToast({
      title: error,
      duration: 2000,
      icon: 'none',
    })
  }
}
